package com.example.springbootbabyu.intercepter;
import com.example.springbootbabyu.utils.JwtTokenUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;

@Slf4j
public class JwtAuthenticationInterceptor implements HandlerInterceptor {

    private final JwtTokenUtil jwtTokenUtil;

    public JwtAuthenticationInterceptor(JwtTokenUtil jwtTokenUtil) {
        this.jwtTokenUtil = jwtTokenUtil;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (HttpMethod.OPTIONS.matches(request.getMethod())) {
            return true;
        }
        // 1. 获取当前请求路径
        String path = request.getRequestURI().substring(request.getContextPath().length());

        // 2. 检查是否属于排除路径（如 /user/**）
//        log.info("path: " + path);
        if (isExcludePath(path)) {
            return true; // 直接放行排除路径
        }
        String authHeader = request.getHeader("Authorization");
//        log.info("authHeader: " + authHeader);
        if (authHeader == null || !authHeader.startsWith("Bearer ")) {
            sendUnauthorized(response, "缺少有效的认证token");
            return false;
        }
        String token = authHeader.substring(7);
        // 验证token
        if (!jwtTokenUtil.validateToken(token)) {
            sendUnauthorized(response, "无效或过期的token");
            return false;
        }

        // 刷新token过期时间
        jwtTokenUtil.refreshToken(token);
        // 将用户信息存入request
        String userId = jwtTokenUtil.getUserIdFromToken(token);
//        log.info("userId: " + userId);
        String username = jwtTokenUtil.getUsernameFromToken(token);

        request.setAttribute("userId", userId);
        request.setAttribute("username", username);
        return true;
    }

    private void sendUnauthorized(HttpServletResponse response, String message) throws IOException {
        // 中文乱码问题
        response.setHeader("Content-Type", "application/json;charset=UTF-8");
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.setContentType("application/json");
        response.getWriter().write("{\"code\": 401, \"message\": \"" + message + "\"}");
    }
    // 判断是否为排除路径的方法
    private boolean isExcludePath(String path) {
        // 这里应该匹配您在WebConfig中配置的排除路径规则
        return path.startsWith("/user/")
                || path.startsWith("/home/")
                || path.startsWith("/category/")
                || path.startsWith("/goods/")
                || path.startsWith("/chat/");
    }
}